/*
 Copyright (c) 2013-2016 Chukong Technologies Inc.
 Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd.

 http://www.cocos.com

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated engine source code (the "Software"), a limited,
  worldwide, royalty-free, non-assignable, revocable and non-exclusive license
 to use Cocos Creator solely to develop games on your target platforms. You shall
  not use Cocos Creator software for developing other software or tools that's
  used for developing games. You are not granted to publish, distribute,
  sublicense, and/or sell copies of Cocos Creator.

 The software or tools in this License Agreement are licensed, not sold.
 Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/
// import Cache   from "./cache"

const BASE64_KEYS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
const values:number[] = new Array(123); // max char code in base64Keys
for (let i = 0; i < 123; ++i) { values[i] = 64; } // fill with placeholder('=') index
for (let i = 0; i < 64; ++i) { values[BASE64_KEYS.charCodeAt(i)] = i; }

// decoded value indexed by base64 char code
 const BASE64_VALUES = values;
// // import { TEST } from 'internal:constants';
// import { BASE64_VALUES } from './misc';
// // import { legacyCC } from '../global-exports';

const HexChars = '0123456789abcdef'.split('');

const _t = ['', '', '', ''];
const UuidTemplate = _t.concat(_t, '-', _t, '-', _t, '-', _t, '-', _t, _t, _t);
const Indices = UuidTemplate.map((x, i) => (x === '-' ? NaN : i)).filter(isFinite);
// import { normalize } from './helper';
export interface IConfigOption {
    importBase: string;
    nativeBase: string;
    base: string;
    name: string;
    deps: string[];
    uuids: string[];
    paths: Record<string, any[]>;
    scenes: Record<string, string>;
    packs: Record<string, string[]>;
    versions: { import: string[], native: string[] };
    redirect: string[];
    debug: boolean;
    types: string[];
    extensionMap: Record<string, string[]>;
}

export interface IAssetInfo {
    uuid: string;
    packs?: IPackInfo[];
    redirect?: string;
    ver?: string;
    nativeVer?: string;
    extension?: string;
}

export interface IPackInfo extends IAssetInfo {
    packedUuids: string[];
    ext: string;
}

export interface IAddressableInfo extends IAssetInfo {
    path: string;
    // ctor: AssetType;
}

export interface ISceneInfo extends IAssetInfo {
    url: string;
}
/**
 * @en
 * Decode uuid, returns the original uuid
 *
 * @zh
 * 解码 uuid，返回原始 uuid
 *
 * @param  base64 - the encoded uuid
 * @returns the original uuid
 *
 * @example
 * ```ts
 * const uuid = 'fcmR3XADNLgJ1ByKhqcC5Z';
 * const originalUuid = decodeUuid(uuid); // fc991dd7-0033-4b80-9d41-c8a86a702e59
 * ```
 */
export default function decodeUuid (base64: string) {
    const strs = base64.split('@');
    const uuid = strs[0];
    if (uuid.length !== 22) {
        return base64;
    }
    UuidTemplate[0] = base64[0];
    UuidTemplate[1] = base64[1];
    for (let i = 2, j = 2; i < 22; i += 2) {
        const lhs = BASE64_VALUES[base64.charCodeAt(i)];
        const rhs = BASE64_VALUES[base64.charCodeAt(i + 1)];
        UuidTemplate[Indices[j++]] = HexChars[lhs >> 2];
        UuidTemplate[Indices[j++]] = HexChars[((lhs & 3) << 2) | rhs >> 4];
        UuidTemplate[Indices[j++]] = HexChars[rhs & 0xF];
    }
    return base64.replace(uuid, UuidTemplate.join(''));
}


export const processOptions = (options: any) => {
    // if (EDITOR || TEST) { return; }
    let uuids = options.uuids;
    const paths = options.paths;
    const types = options.types;
    const bundles = options.deps;
    const realEntries = options.paths = Object.create(null);

    if (options.debug === false) {
        for (let i = 0, l = uuids.length; i < l; i++) {
            uuids[i] = decodeUuid(uuids[i]);
        }

        for (const id in paths) {
            const entry = paths[id];
            const type = entry[1];
            entry[1] = types[type];
        }
    } else {
        const out = Object.create(null);
        for (let i = 0, l = uuids.length; i < l; i++) {
            const uuid = uuids[i];
            uuids[i] = out[uuid] = decodeUuid(uuid);
        }
        uuids = out;
    }

    for (const id in paths) {
        const entry = paths[id];
        realEntries[uuids[id]] = entry;
    }

    const scenes = options.scenes;
    for (const name in scenes) {
        const uuid = scenes[name];
        scenes[name] = uuids[uuid];
    }

    const packs = options.packs;
    for (const packId in packs) {
        const packedIds = packs[packId];
        for (let j = 0; j < packedIds.length; ++j) {
            packedIds[j] = uuids[packedIds[j]];
        }
    }

    const versions = options.versions;
    if (versions) {
        for (const folder in versions) {
            const entries = versions[folder];
            for (let i = 0; i < entries.length; i += 2) {
                const uuid = entries[i];
                entries[i] = uuids[uuid] || uuid;
            }
        }
    }

    const redirect = options.redirect;
    if (redirect) {
        for (let i = 0; i < redirect.length; i += 2) {
            redirect[i] = uuids[redirect[i]];
            redirect[i + 1] = bundles[redirect[i + 1]];
        }
    }

    const extensionMap = options.extensionMap;
    if (extensionMap) {
        for (const ext in options.extensionMap) {
            if (!Object.prototype.hasOwnProperty.call(options.extensionMap, ext)) {
                continue;
            }
            options.extensionMap[ext].forEach((uuid:string, index:string) => {
                options.extensionMap[ext][index] = uuids[uuid] || uuid;
            });
        }
    }
    return options
};


// let a:any ={"importBase":"import","nativeBase":"native","name":"b2","deps":[],"uuids":["01J2DU0rNP8ZvwWK1SqJDz","078ca7473","0a8Ho2jkVNrY+pYM4polqM","4f2dHtKfVEzr58j6s6HpRH","4f2dHtKfVEzr58j6s6HpRH@6c48a","4f2dHtKfVEzr58j6s6HpRH@f9941","a0lX8rLDNCw5zGA8o2daWK","a0lX8rLDNCw5zGA8o2daWK@6c48a","a0lX8rLDNCw5zGA8o2daWK@f9941","d0cLbl8WdAbIZ6nY4Y4H5e","d0cLbl8WdAbIZ6nY4Y4H5e@6c48a","d0cLbl8WdAbIZ6nY4Y4H5e@f9941","d8qiYZgsBBrL3Ip7GzXYYU","d8qiYZgsBBrL3Ip7GzXYYU@6c48a","d8qiYZgsBBrL3Ip7GzXYYU@f9941"],"paths":{"0":["folder/It_Ludo_Ash",3],"2":["folder/It_Ludo_Ash",4],"3":["b2/`",0],"4":["b2/`/texture",1,1],"5":["b2/`/spriteFrame",2,1],"6":["1d9d32a3e",0],"7":["1d9d32a3e/texture",1,1],"8":["1d9d32a3e/spriteFrame",2,1],"9":["6/6",0],"10":["6/6/texture",1,1],"11":["6/6/spriteFrame",2,1],"12":["folder/It_Ludo_Ash",0],"13":["folder/It_Ludo_Ash/texture",1,1],"14":["folder/It_Ludo_Ash/spriteFrame",2,1]},"scenes":{},"packs":{"078ca7473":["0","2","3","4","5","6","7","8","9","10","11","12","13","14"]},"versions":{"import":[],"native":[]},"redirect":[],"debug":false,"extensionMap":{},"types":["cc.ImageAsset","cc.Texture2D","cc.SpriteFrame","cc.Asset","sp.SkeletonData"]}
// // if (TEST) {
// //     legacyCC._Test.decodeUuid = decodeUuid;
// // }
// let uuid = decodeUuid("6cRIHtSv5FS73vNtXImLs")
// console.warn(processOptions(a))
// console.warn("uuid",uuid)
// // new Cache